package com.c8a.validation.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import javax.validation.ValidationException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author C8A
 * @Date 2022-04-23 22:00
 * @Email 1912327276@qq.com
 */

@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * {
     * "timestamp": "2021-09-10T16:20:05.794+00:00",
     * "status": 400,
     * "error": "Bad Request",
     * "path": "/valid1"
     * }
     * 由于返回结构并不是我们希望的所以需要特别处理下:
     * {
     * "id": "id不能为空"
     * }
     *
     * @param e MethodArgumentNotValidException:控制层校验异常
     * @return ResponseEntity
     */
    @ExceptionHandler
    public ResponseEntity<?> exceptionHandler(MethodArgumentNotValidException e) {

        Map<String, String> error = e.getBindingResult().getFieldErrors()
                .stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (var1, var2) -> var1));
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);

    }

    /**
     * 补充实现层异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler
    public ResponseEntity<?> exceptionHandler1(ConstraintViolationException e) {
        /**
         * id --主键不能有值
         */
        Map<Path, String> error = e.getConstraintViolations()
                .stream()
                .collect(Collectors.toMap(ConstraintViolation::getPropertyPath, ConstraintViolation::getMessage, (var1, var2) -> var1));
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
    }

}
